package com.heima.user.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.service.ApUserService;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.nio.charset.StandardCharsets;
import java.util.HashMap;
@Service
public class ApUserServiceImpl extends ServiceImpl<ApUserMapper, ApUser>implements ApUserService {
    /**
     * 登录校验
     * @return
     */
    @Override
    public ResponseResult login(LoginDto dto) {
        //1.正常登录（手机号+密码登录）
        String phone = dto.getPhone();
        String password = dto.getPassword();
        if (!StringUtils.isBlank(phone)&&!StringUtils.isBlank(password)){
            LambdaQueryWrapper<ApUser> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ApUser::getPhone,phone);
            ApUser apUser = getOne(wrapper);
            if (apUser==null){
                //用户不存在
             return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
            }
            //根据手机号查询的用户的盐
            String salt = apUser.getSalt();
            //根据手机号查询的用户的密码
            String pswd = apUser.getPassword();
            //给请求参数中的密码加盐后通过MD5加密
            password= DigestUtils.md5DigestAsHex((password+salt).getBytes(StandardCharsets.UTF_8));
            if (!pswd.equals(password)){
                //如果密码不匹配
                return ResponseResult.errorResult( AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
            }
            HashMap<String, Object> map = new HashMap<>();
            //存入token
            map.put("token",AppJwtUtil.getToken(apUser.getId().longValue()));
            apUser.setSalt("");
            apUser.setPassword("");
            map.put("user",apUser);
            ResponseResult result = ResponseResult.okResult(map);
            return result;
        }else {
            //2.游客登录
            HashMap<String, Object> map = new HashMap<>();
            map.put("token",AppJwtUtil.getToken(0L));
            return ResponseResult.okResult(map);
        }
    }

}
